//
//  HomeVideoPlayViewController.m
//  WallpaperHdLib
//
//  Created by 9haomi on 2021/2/27.
//

#import "HomeVideoPlayViewController.h"
#import "SmallVideoPlayCell.h"
#import "SmallVideoModel.h"
#import "DDVideoPlayerManager.h"
#import "SetingViewController.h"
#import <KFCircleMenu.h>

#import "CategoryViewController.h"
#import "DiyViewController.h"
#import "DownloadViewController.h"

static NSString * const SmallVideoCellIdentifier = @"SmallVideoCellIdentifier";

@interface HomeVideoPlayViewController ()<UITableViewDataSource, UITableViewDelegate, ZFManagerPlayerDelegate, SmallVideoPlayCellDlegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *fatherView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, assign) NSInteger currentPlayIndex;
@property (nonatomic, assign) NSInteger skip;//从第几个开始（页*limit）
@property (nonatomic, assign) NSInteger limit;//每页加载几个
@property (nonatomic, strong) NSString *mainUrl;
//这个是播放视频的管理器
@property (nonatomic, strong) DDVideoPlayerManager *videoPlayerManager;
//这个是预加载视频的管理器
@property (nonatomic, strong) DDVideoPlayerManager *preloadVideoPlayerManager;

//多功能旋转菜单
@property (nonatomic, strong) KFCircleMenu *circleMenu2;
@end

@implementation HomeVideoPlayViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self cteateBottomUI];
    [self circleMenuUI];
    [self getCategory];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.videoPlayerManager autoPause];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.videoPlayerManager autoPlay];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)circleMenuUI {
    
    WEAKSELF(weakSelf);
    
    self.circleMenu2 = [[KFCircleMenu alloc] initWithFrame:CGRectMake(ScreenWidth/2-150/2, ScreenHeight-170, 150, 150)];
    self.circleMenu2.centerButtonSize = CGSizeMake(45, 45);
    self.circleMenu2.isOpened = NO;
        [self.circleMenu2 loadButtonWithIcons:@[
                                                [UIImage imageNamed:@"分类"],
                                                [UIImage imageNamed:@"设置"],
                                                [UIImage imageNamed:@"收藏"],
                                                [UIImage imageNamed:@"预览"],
                                                [UIImage imageNamed:@"DIY"],
                                                [UIImage imageNamed:@"下载"],
                                                [UIImage imageNamed:@"帮助"]
                                                ]
                            innerCircleRadius:30];
        [self.circleMenu2 setButtonClickBlock:^(NSInteger idx) {
            NSLog(@"button %@ clicked !",@(idx));
            
            [weakSelf jumpToVC:idx];
        }];
        
        [self.circleMenu2 setCenterIcon:[UIImage imageNamed:@"加号"]];
        [self.circleMenu2 setCenterIconType:KFIconTypeCustomImage];
        
        self.circleMenu2.tintColor = [UIColor whiteColor];
        self.circleMenu2.mainColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
    [self.view addSubview:self.circleMenu2];
}

-(void)jumpToVC:(NSInteger)index{

    switch (index) {
        case 0:{
            CategoryViewController *categoryVC = [[CategoryViewController alloc] init];
            [self.navigationController pushViewController:categoryVC animated:YES];
        }
            break;
        case 1:{
            SetingViewController *setview = [[SetingViewController alloc] init];
            [self.navigationController pushViewController:setview animated:YES];
        }
            break;
        case 2:
            
            break;
        case 3:
            
            break;
        case 4:{
            DiyViewController *diyVC = [[DiyViewController alloc] init];
            [self.navigationController pushViewController:diyVC animated:YES];
        }
            break;
        case 5:{
            DownloadViewController *downloadVC = [[DownloadViewController alloc] init];
            [self.navigationController pushViewController:downloadVC animated:YES];
        }
            break;
        default:
            break;
    }
}


- (void)cteateBottomUI{
    //右侧渐变颜色
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0 , SCREEN_HEIGHT-100, SCREEN_WIDTH ,100);
    //colors存放渐变的颜色的数组
    gradientLayer.colors=@[(__bridge id)RGBA(0, 0, 0, 0.0).CGColor,(__bridge id)RGBA(0, 0, 0, 0.5).CGColor,(__bridge id)RGBA(0, 0, 0, 1.0).CGColor];
//        gradientLayer.locations = @[@0.3, @0.5, @1.0];
    /**
     * 起点和终点表示的坐标系位置，(0,0)表示左上角，(1,1)表示右下角
     */
    //默认是从上往下的
    //gradientLayer.startPoint = CGPointMake(0, 0);
    //gradientLayer.endPoint = CGPointMake(1, 1);
    //    layer.frame = self.messageLabel.bounds;
    [self.view.layer addSublayer:gradientLayer];
}

- (void)createUI {
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.pagingEnabled = YES;
    self.tableView.scrollsToTop = NO;
    [self.view addSubview:self.tableView];
    [self.view sendSubviewToBack:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.estimatedRowHeight = SCREEN_HEIGHT;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.backgroundColor = [UIColor blackColor];
    [self.tableView registerClass:[SmallVideoPlayCell class] forCellReuseIdentifier:SmallVideoCellIdentifier];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.with.offset(0);
    }];
    if(@available(iOS 11.0, *)){
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentPlayIndex inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self playIndex:self.currentPlayIndex];
        if(self.modelArray.count > (self.currentPlayIndex + 1)) {
            [self preLoadIndex:self.currentPlayIndex + 1];
        }
//    });
    
    
}

- (NSMutableArray *)modelArray {
    if(!_modelArray) {
        _modelArray = [NSMutableArray array];
        
    }
    return _modelArray;
}

- (void)getCategory {
    
    NSMutableDictionary * mdic = [NSMutableDictionary dictionary];

    [HttpNetworkTool GET:WallpaperCategoryList  ReadCache:YES Parameters:mdic Success:^(id data) {

        if ([[data valueForKey:@"code"] integerValue] ==0) {
            NSArray *recommend = data[@"res"][@"video"];
            for (int i = 0; i<recommend.count; i++) {
                NSString *title = recommend[i][@"name"][@"zh-cn"];
                if ([title isEqualToString:@"科幻"]) {
                    self.mainUrl = recommend[i][@"url"];
                }
            }
            [self getResource];
        }else{
            [self getResource];
        }

    } Failure:^(NSError *error) {
        [self getResource];
    }];
}

- (void)getResource {
    
    self.skip = 0;
    self.limit = 21;
    
    NSMutableDictionary * mdic = [NSMutableDictionary dictionary];
    [mdic setValue:@(self.skip) forKey:@"skip"];
    [mdic setValue:@(self.limit) forKey:@"limit"];
    
    NSString *url = HomeWallpaperList;
    if (self.mainUrl.length>0) {
        url = self.mainUrl;
    }
    
    [HttpNetworkTool GET:url  ReadCache:YES Parameters:mdic Success:^(id data) {

        if ([[data valueForKey:@"code"] integerValue] ==0) {
            
            NSMutableArray *videowp = [NSMutableArray array];

            if ([url isEqualToString:HomeWallpaperList]) {
                videowp = data[@"res"][@"videowp"];
            }else{
                videowp = data[@"res"];
            }

            for (int i = 0; i<videowp.count; i++) {
                SmallVideoModel * model = [SmallVideoModel yy_modelWithJSON:videowp[i]];
                model.aspect = 1.5;
                [self.modelArray addObject:model];
            }

            if (self.modelArray.count>0) {
                self.skip++;
                [self createUI];
            }
            
        }else{
        }

    } Failure:^(NSError *error) {
    }];
    
}

- (void)getMoreResource {
    NSMutableDictionary * mdic = [NSMutableDictionary dictionary];
    [mdic setValue:@(self.skip*self.limit) forKey:@"skip"];
    [mdic setValue:@(self.limit) forKey:@"limit"];
    
    NSString *url = HomeWallpaperList;
    if (self.mainUrl.length>0) {
        url = self.mainUrl;
    }
    
    [HttpNetworkTool GET:url  ReadCache:YES Parameters:mdic Success:^(id data) {

        if ([[data valueForKey:@"code"] integerValue] ==0) {
            
            NSArray *videowp = [[NSArray alloc] init];
            
            if ([url isEqualToString:HomeWallpaperList]) {
                videowp = data[@"res"][@"videowp"];
            }else{
                videowp = data[@"res"];
            }
            
            for (int i = 0; i<videowp.count; i++) {
                SmallVideoModel * model = [SmallVideoModel yy_modelWithJSON:videowp[i]];
                model.aspect = 1.5;
                [self.modelArray addObject:model];
            }
            
            if (self.modelArray.count>0) {
                self.skip++;
                [self.tableView reloadData];
            }
            
        }else{
        }

    } Failure:^(NSError *error) {
    }];
}

#pragma mrak - UITableViewDataSource & UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SmallVideoPlayCell *cell = [tableView dequeueReusableCellWithIdentifier:SmallVideoCellIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    cell.model = self.modelArray[indexPath.row];
    //NSInteger rowIndex = indexPath.row;
    //NSInteger index = self.modelArray.count - 2;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SCREEN_HEIGHT;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentIndex = round(self.tableView.contentOffset.y / SCREEN_HEIGHT);
    if(self.currentPlayIndex != currentIndex) {
        if(self.currentPlayIndex > currentIndex) {
            [self preLoadIndex:currentIndex-1];
        } else if(self.currentPlayIndex < currentIndex) {
            [self preLoadIndex:currentIndex+1];
        }
        self.currentPlayIndex = currentIndex;
        [self playIndex:self.currentPlayIndex];
    }
    if (currentIndex == self.modelArray.count-1) {
        //开始请求下一页内容
        NSLog(@"****开始请求下一页内容*****");
        [self getMoreResource];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    CGFloat currentIndex = self.tableView.contentOffset.y / SCREEN_HEIGHT;
    if(fabs(currentIndex - self.currentPlayIndex)>1) {
        [self.videoPlayerManager resetPlayer];
        [self.preloadVideoPlayerManager resetPlayer];
    }
}

- (void)playIndex:(NSInteger)currentIndex {
    SmallVideoPlayCell *currentCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:currentIndex inSection:0]];
    
    NSString *artist = nil;
    NSString *title = nil;
    NSString *cover_url = nil;
    NSURL *videoURL = nil;
    NSURL *originVideoURL = nil;
    BOOL useDownAndPlay = NO;
    AVLayerVideoGravity videoGravity = AVLayerVideoGravityResizeAspect;
    
    //关注,推荐
    SmallVideoModel *currentPlaySmallVideoModel = self.modelArray[currentIndex];
    
    artist = currentPlaySmallVideoModel.artist;
    title = currentPlaySmallVideoModel.name;
    cover_url = currentPlaySmallVideoModel.cover_url;
    videoURL = [NSURL URLWithString:currentPlaySmallVideoModel.video_url];
    originVideoURL = [NSURL URLWithString:currentPlaySmallVideoModel.video_url];
    useDownAndPlay = YES;
    if(currentPlaySmallVideoModel.aspect >= 1.4) {
        videoGravity = AVLayerVideoGravityResizeAspectFill;
    } else {
        videoGravity = AVLayerVideoGravityResizeAspect;
    }
        
    self.fatherView = currentCell.playerFatherView;
    self.videoPlayerManager.playerModel.videoGravity = videoGravity;
    self.videoPlayerManager.playerModel.fatherView       = self.fatherView;
    self.videoPlayerManager.playerModel.title            = title;
    self.videoPlayerManager.playerModel.artist = artist;
    self.videoPlayerManager.playerModel.placeholderImageURLString = cover_url;
    self.videoPlayerManager.playerModel.videoURL         = videoURL;
    self.videoPlayerManager.originVideoURL = originVideoURL;
    self.videoPlayerManager.playerModel.useDownAndPlay = YES;
    //如果设备存储空间不足200M,那么不要边下边播
    if([self deviceFreeMemorySize] < 200) {
        self.videoPlayerManager.playerModel.useDownAndPlay = NO;
    }
    [self.videoPlayerManager resetToPlayNewVideo];
}

- (CGFloat)deviceFreeMemorySize {
    /// 总大小
    float totalsize = 0.0;
    /// 剩余大小
    float freesize = 0.0;
    /// 是否登录
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    if (dictionary)
    {
        NSNumber *_free = [dictionary objectForKey:NSFileSystemFreeSize];
        freesize = [_free unsignedLongLongValue]*1.0/(1024);
        
        NSNumber *_total = [dictionary objectForKey:NSFileSystemSize];
        totalsize = [_total unsignedLongLongValue]*1.0/(1024);
    } else
    {
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
    }
    return freesize/1024.0;
}

//预加载
- (void)preLoadIndex:(NSInteger)index {
    [self.preloadVideoPlayerManager resetPlayer];
    if(self.modelArray.count <= index || [self deviceFreeMemorySize] < 200  || index<0) {
        return;
    }
    NSString *artist = nil;
    NSString *title = nil;
    NSString *cover_url = nil;
    NSURL *videoURL = nil;
    NSURL *originVideoURL = nil;
    BOOL useDownAndPlay = NO;
    
    //关注,推荐
    SmallVideoModel *currentPlaySmallVideoModel = self.modelArray[index];
    artist = currentPlaySmallVideoModel.artist;
    title = currentPlaySmallVideoModel.name;
    cover_url = currentPlaySmallVideoModel.cover_url;
    videoURL = [NSURL URLWithString:currentPlaySmallVideoModel.video_url];
    originVideoURL = [NSURL URLWithString:currentPlaySmallVideoModel.video_url];
    useDownAndPlay = YES;
    
    self.preloadVideoPlayerManager.playerModel.title            = title;
    self.preloadVideoPlayerManager.playerModel.artist = artist;
    self.preloadVideoPlayerManager.playerModel.placeholderImageURLString = cover_url;
    self.preloadVideoPlayerManager.playerModel.videoURL         = videoURL;
    self.preloadVideoPlayerManager.originVideoURL = originVideoURL;
    self.preloadVideoPlayerManager.playerModel.useDownAndPlay = YES;
    self.preloadVideoPlayerManager.playerModel.isAutoPlay = NO;
    [self.preloadVideoPlayerManager resetToPlayNewVideo];
}



#pragma mark - SmallVideoPlayCellDlegate

//评论
- (void)handleCommentVidieoModel:(SmallVideoModel *)smallVideoModel {

}


#pragma mark - Action
- (void) backToPreviousView:(id)sender;
{
    [self.videoPlayerManager resetPlayer];
    [self.preloadVideoPlayerManager resetPlayer];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - LazyLoad

- (DDVideoPlayerManager *)videoPlayerManager {
    if(!_videoPlayerManager) {
        _videoPlayerManager = [[DDVideoPlayerManager alloc] init];
        _videoPlayerManager.managerDelegate = self;
    }
    return _videoPlayerManager;
}

- (DDVideoPlayerManager *)preloadVideoPlayerManager {
    if(!_preloadVideoPlayerManager) {
        _preloadVideoPlayerManager = [[DDVideoPlayerManager alloc] init];
    }
    return _preloadVideoPlayerManager;
}

#pragma mark - dealloc
- (void)dealloc {
    [self.videoPlayerManager resetPlayer];
    [self.preloadVideoPlayerManager resetPlayer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
